package com.deercrowing.takeaway.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.util.Calendar;

@Slf4j
@Configuration
public class CounterIDGenerator {

    private static Integer counter;
    private String currentDate;

    public CounterIDGenerator() {
        this.counter = 1; // 从001开始计数
        this.currentDate = getCurrentDate();
    }

    public String generateID() {
        String id = currentDate + String.format("%03d", counter);
        incrementCounter();
        return id;
    }

    private void incrementCounter() {
        counter++;
        if (counter > 999) {
            counter = 1; // 计数器超过999后重置
        }
        checkDateChange();
    }

    private void checkDateChange() {
        String newDate = getCurrentDate();
        if (!newDate.equals(currentDate)) {
            currentDate = newDate;
            counter = 1; // 新的一天计数器重置为001
        }
    }

    private String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(Calendar.getInstance().getTime());
    }
}
